/**
 * @description 登录、获取用户信息、退出登录、清除token逻辑，不建议修改
 */
import { User } from '~/src/api/interface/user'
import piniaPersistConfig from '~/src/config/piniaPersist'
import { UserModuleType } from '~/types/store'
import { UserState } from '../interface'
import { useAclStore } from './acl'
import { useSettingsStore } from './settings'
import { useTabsStore } from './tabs'
import { getUserInfo, login } from '/@/api/user'
import { storage } from '/@/config'
import { removeToken } from '/@/utils/token'
import { gp } from '/@vab/plugins/vab'

export const useUserStore = defineStore('user', {
  state: (): UserModuleType => ({
    token: '',
    username: '游客',
    avatar: './static/svg/avatar.svg',
    userInfo: {},
    store: {},
    editUserInfo: {},
  }),
  getters: {
    getToken: (state) => state.token,
    getUsername: (state) => state.username,
    getAvatar: (state) => state.avatar,
    getEditUserInfo: (state) => state.editUserInfo,
  },
  actions: {
    /**
     * @description 设置token
     * @param {*} token
     */
    setToken(token: string) {
      this.token = token
    },
    setUserInfo(userInfo: UserState['userInfo']) {
      this.userInfo = userInfo
    },
    setStore(store: UserState['store']) {
      this.store = store
    },
    /**
     * @description 设置用户名
     * @param {*} username
     */
    setUsername(username: string) {
      this.username = username
      username
    },
    setEditUserInfo(editUserInfo: User.UserInfo) {
      this.editUserInfo = editUserInfo
    },
    /**
     * @description 设置头像
     * @param {*} avatar
     */
    setAvatar(avatar: string) {
      this.avatar = avatar
    },
    /**
     * @description 登录拦截放行时，设置虚拟角色
     */
    setVirtualRoles() {
      const aclStore = useAclStore()
      aclStore.setFull(true)
      this.setUsername('admin(未开启登录拦截)')
      this.setAvatar('./static/svg/avatar.svg')
    },
    /**
     * @description 设置token并发送提醒
     * @param {string} token 更新令牌
     * @param {string} tokenName 令牌名称
     */
    afterLogin(token: string, tokenName: string, store: any, sysUser: any) {
      const settingsStore = useSettingsStore() // 拿到名字
      if (token) {
        this.setToken(token)
        this.setUserInfo(sysUser)
        this.setStore(store)
        this.setAvatar(sysUser.avatar || './static/svg/avatar.svg')
        this.setUsername(sysUser.userName)
        const hour = new Date().getHours()
        const thisTime = hour < 8 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 18 ? '下午好' : '晚上好'
        gp.$baseNotify(`欢迎登录${settingsStore.title}`, `${thisTime}！`)
      } else {
        const err = `登录接口异常，未正确返回${tokenName}...`
        gp.$baseMessage(err, 'error', 'hey')
        throw err
      }
    },
    /**
     * @description 登录
     * @param {*} userInfo
     */
    async login(userInfo: any) {
      const {
        data: { token, sysUser, store },
      } = await login(userInfo)
      this.afterLogin(token.token, 'token', store, sysUser)

      // 登录成功后立即获取用户信息 菜单 和 按钮权限
      // await this.getUserInfo()
    },
    /**
     * @description 获取用户信息接口 这个接口非常非常重要，如果没有明确底层前逻辑禁止修改此方法，错误的修改可能造成整个框架无法正常使用
     * @returns
     */
    async getUserInfo() {
      const { data } = await getUserInfo({})
      if (!data) {
        const err = 'getUserInfo核心接口异常，请检查返回JSON格式是否正确'
        gp.$baseMessage(err, 'error', 'hey')
        throw err
      } else {
        this.setEditUserInfo(data)
      }
    },
    /**
     * @description 退出登录
     */
    async logout() {
      // await logout()
      await this.resetAll()
    },
    /**
     * @description 重置token、roles、permission、router、tabsBar等
     */
    async resetAll() {
      const aclStore = useAclStore()
      const tabsStore = useTabsStore()

      // 清除token
      await removeToken(storage)
      this.setToken('')
      this.setUserInfo({})
      this.setStore({})
      this.setAvatar('./static/svg/avatar.svg')
      // this.username('游客')

      // 清空权限和角色
      await aclStore.setPermission([])
      await aclStore.setFull(false)
      await aclStore.setRole([])

      // 清除tabs
      await tabsStore.delAllVisitedRoutes()

      // 清除localStorage中的相关缓存
      if (storage === 'localStorage') {
        // 只移除用户相关数据，不影响主题等设置
        localStorage.removeItem('caughtRoutes')
      }
      // 重置用户信息
      this.setUsername('游客')
      this.setAvatar('./static/svg/avatar.svg')
    },
  },
  persist: piniaPersistConfig('my-user'),
})
